from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import InvalidToken, AuthenticationFailed
from django.utils.translation import gettext_lazy as _
import jwt
# 自定义的用户模型
from admincharge.models import ChargeAdmin
from rest_framework_simplejwt.tokens import RefreshToken


class MyJWTAuthentication(JWTAuthentication):
    def authenticate(self, request):
        try:
            user,token = super().authenticate(request)
            # print(token)
            self.check_token_expiry(token)
        except AuthenticationFailed as e:
            if 'Token has expired' in str(e):
                # 刷新 Token 并重新验证
                refreshed_token = self.refresh_token(request)
                user, token = super().authenticate(request, refreshed_token)
            else:
                raise e
        return user, token

    def check_token_expiry(self, token):
        # 检查 Token 是否过期
        if token and token['exp']:
            expiration_timestamp = token['exp']
            now_timestamp = self.get_timestamp_now()
            if expiration_timestamp < now_timestamp:
                raise AuthenticationFailed('Token has expired')

    def refresh_token(self, request):
        # 从请求中获取浏览器返回的 Token
        raw_token = self.get_raw_token(request)
        if raw_token:
            refresh = RefreshToken(raw_token)
            refreshed_token = str(refresh.access_token)
            return refreshed_token
        raise AuthenticationFailed('Token not provided in the request')

    def get_timestamp_now(self):
        # 获取当前时间戳
        from datetime import datetime
        return int(datetime.utcnow().timestamp())

    def get_raw_token(self, request):
        # 从请求中获取 Token
        # print('request',str(request))
        #  b'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA1NDU5NTI4LCJpYXQiOjE3MDU0NTkzNDgsImp0aSI6IjUxZmUwMzRhZGVhNTRmOTZiM
        # TJmMTdiOWY1NjM2MGRjIiwidXNlcl9pZCI6MX0.vuAqSbTb4F3WBnWosMnJR4hexiwdUbzyYkQ5C9JEcjA'
        authorization_header = request
        if authorization_header:
            return authorization_header.decode('utf-8').split(' ')[1]  # 提取 Token 部分
        return None
